package com.zhong.encrypt;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.zhong.encrypt.Utils.RSAUtil;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

public class RSAActivity extends AppCompatActivity {
    private static final String TAG = RSAActivity.class.getSimpleName();

    private TextView logTextView;
    private EditText keyLengthEt;            //种子
    private EditText textEt;
    private Button secretBtn;
    private Button decryptBtn;

    PublicKey publicKey;        //公钥
    PrivateKey privateKey;      //私钥
    byte[] secretByte;          //密文

    /** 秘钥 */
    private String privateKeyStr = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKQC6pvJegfUt/Jxa/BznLsZ5xpf" +
            "h6f//aA8E2QhIgxS0lmFRal693PylMnVceBPsKJvWVZ2IAnXS3xrEtT/m31qXS5DKv8U9Lyysai6" +
            "7VSY8hb+6HSf7+robCvFc0Z9VW8vVytS/wVYtdFqAgwXW2SlRirV8IM8Q1440f5jZP2xAgMBAAEC" +
            "gYATkIR/enB75ChgO57yYzwwRoX+q6QhSoRs+5WdlWU8HpoYkzEM504C7w5IKFXJ+f+aVNmNmpA2" +
            "VFAdIqGvtmEMCz2yrmEw1/7ShJp59prugCx1dy/y4UJMvW4lG2nVcBT5dg3H+8kmze6PdS1oAWzc" +
            "NpV8tbODXquWTo8VuMOdcQJBANN4UUw7nykQLsJPTZJ6pjIRjI6jNNGKV9n2A0kEh6Gbapzs963L" +
            "68UYF9680qgGaBNHvR3z9Ya/T+goc6QXHHkCQQDGjEFJn3V+tlMpkSwoGXHoi10nfLXn8vrYd5kG" +
            "IaZkQXhiqcsRm+aH9GxlFbhliYGzcg2iwoRjBZumc79b0az5AkA3AzDbDROdohkX8XtzpLaBhfEz" +
            "1h9Sd5PdHtPB9gy2rPCyPC8+pjMChf8HscV3cps2kM4Q8bsov7Iw6f0TbfO5AkBInk/av6nXuJPe" +
            "JizCVdwls6NUp/ZYabR5q/SaG4CiNpfzbirJu/2rSCjFKBaTfKGlold+airFlO2DCd65lIzxAkAR" +
            "xfOyAzx1g9TLk2G17ymxjL2qTSZyfnD7ZOVSkevVw4+9Mx69SoXomZJZZVi5fVJLD7j5NwP0nFDe" +
            "f/JgFiZs";

    /** 公钥 */
    private String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCkAuqbyXoH1LfycWvwc5y7GecaX4en//2gPBNk" +
            "ISIMUtJZhUWpevdz8pTJ1XHgT7Cib1lWdiAJ10t8axLU/5t9al0uQyr/FPS8srGouu1UmPIW/uh0" +
            "n+/q6GwrxXNGfVVvL1crUv8FWLXRagIMF1tkpUYq1fCDPENeONH+Y2T9sQIDAQAB";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rsa);

        initView();
    }

    private void initView() {
        logTextView = findViewById(R.id.log_tv);
        keyLengthEt = findViewById(R.id.key_length_et);
        textEt = findViewById(R.id.text_et);
        secretBtn = findViewById(R.id.secret_btn);
        decryptBtn = findViewById(R.id.decrypt_btn);

        secretBtn.setOnClickListener(onClickListener);
        decryptBtn.setOnClickListener(onClickListener);
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.secret_btn:
                    String keyLengthStr = keyLengthEt.getText().toString().trim();
                    String textStr = textEt.getText().toString().trim();

                    if (TextUtils.isEmpty(keyLengthStr) || TextUtils.isEmpty(textStr)) {
                        return;
                    }

                    int keyLength = Integer.parseInt(keyLengthStr);
                    if (keyLength < 512 && keyLength > 2048) {
                        showLog("非法的秘钥长度", true);
                        return;
                    }

                    try {
                        KeyPair keyPair = RSAUtil.generateKey(keyLength);
                        publicKey = keyPair.getPublic();
                        privateKey = keyPair.getPrivate();

                        //秘钥字符串生成Key需要通过Base64转换为byte[]
//                        publicKey = RSAUtil.getPublicKey(Base64.decode(publicKeyStr, Base64.DEFAULT));
//                        privateKey = RSAUtil.getPrivateKey(Base64.decode(privateKeyStr, Base64.DEFAULT));

                        showLog("公钥：" + Base64.encodeToString(publicKey.getEncoded(), Base64.DEFAULT), false);
                        showLog("私钥：" + Base64.encodeToString(privateKey.getEncoded(), Base64.DEFAULT), true);

                        secretByte = RSAUtil.encrypt(textStr.getBytes(), publicKey);
                        String secretStr = Base64.encodeToString(secretByte, Base64.DEFAULT);
                        showLog("秘钥长度：" + keyLength, true);
                        showLog("明文：" + textStr, true);
                        showLog("密文：" + secretStr, true);
                    } catch (Exception e) {
                        e.printStackTrace();
                        showLog("秘钥创建失败", false);
                    }
                    break;
                case R.id.decrypt_btn:
                    try {
                        if (privateKey != null) {
                            byte[] decryptByte = RSAUtil.decrypt(secretByte, privateKey);
                            String decryptStr = new String(decryptByte);
                            showLog("解密：" + decryptStr, true);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };

    private void showLog(String log, boolean isAppend) {
        Log.d(TAG, log);
        if (isAppend) {
            log = logTextView.getText().toString() + log + "\n";
        } else {
            log += "\n";
        }

        logTextView.setText(log);
    }
}
